package top.dj.job;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: DengJia
 * @Date: 2021/10/22 11:37
 * @Description: 定时数据库备份
 */

@Component
public class ScheduledDataBaseBackup {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
    private static final Logger logger = LoggerFactory.getLogger(ScheduledDataBaseBackup.class);

    @Value("${dbbk.host}")
    private String host; // 数据库地址
    @Value("${dbbk.port}")
    private Integer port; // 数据库端口
    @Value("${dbbk.username}")
    private String username; // 数据库用户名
    @Value("${dbbk.password}")
    private String password; // 数据库密码
    @Value("${dbbk.data-base-name}")
    private String dataBaseName; // 数据库名称
    @Value("${dbbk.data-backup-path}")
    private String dataBackupPath; // 备份路径

    // https://cron.qqe2.com/
    @Scheduled(cron = "0 0 22 * * ?") // 每天晚上10点触发一次
    public void backup() throws IOException, InterruptedException {
        String time = dateFormat.format(new Date());
        logger.info("[{}], 开始备份数据库。", time);
        String fileName = time + "_" + dataBaseName;
        dbBackup(host, port, username, password, dataBackupPath, fileName);
    }

    private void dbBackup(String host, Integer port, String username, String password, String dataBackupPath, String fileName) throws IOException, InterruptedException {
        File file = new File(dataBackupPath);
        if (!file.exists()) {
            file.mkdir();
        }
        File dataFile = new File(file + File.separator + fileName + ".sql");
        if (dataFile.exists()) {
            return;
        }

        // mysqldump -hlocalhost -P3306 -uroot -p123456 db_ms > E:\workspace\dengjia\learning_space\read_write_splitting\src\main\resources\sql\backup.sql
        StringBuffer s = new StringBuffer();
        s.append("cmd /c mysqldump -h").append(host).append(" -P").append(port)
                .append(" -u ").append(username).append(" -p").append(password)
                .append(" ").append(dataBaseName).append(" > ")
                .append(dataFile);
        Process exec = Runtime.getRuntime().exec(s.toString());
        if (exec.waitFor() == 0) {
            logger.info("数据库备份成功，备份路径：{}", dataFile);
        }
    }
}
